//
//  StatisticTableViewController.swift
//  OT Statistic
//
//  Created by Nguyen Van Truong on 1/5/15.
//  Copyright (c) 2015 Nguyen Van Truong. All rights reserved.
//

import UIKit
import CoreData

class StatisticTableViewController: UITableViewController {
    var mang:[String] = ["vvvv"]
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // get current time
        let date = NSDate()
        let calendar = NSCalendar.currentCalendar()
        let components = calendar.components(.CalendarUnitMonth | .CalendarUnitYear, fromDate: date)
        let year = components.year
        let month = components.month
        var strMonth:String = String(month)
        if countElements(strMonth) == 1
        {
            strMonth = "0" + strMonth
        }
        let yearMonth = String(year) + "/" + strMonth
        //Khai bao CSDL
        var appDel:AppDelegate = (UIApplication.sharedApplication().delegate as AppDelegate);
        var context:NSManagedObjectContext = appDel.managedObjectContext!;
        
        //Khoi tao Request
        var request=NSFetchRequest(entityName:"ThongTin");
        request.returnsObjectsAsFaults = false;
        request.predicate = NSPredicate(format: "txtdate contains %@",yearMonth);
        //Lay ket qua tra ve
        var results:NSArray = context.executeFetchRequest(request, error: nil)!;
        //Xu ly ket qua tra ve
        if(results.count>0){
            var textAppend:String = ""
            var dateAppend:String = ""
            var timeAppend:String = ""
            var timeAfterAppend:String = ""
            var timeTotalAppend:Double = 0.0
            var timeAfterTotalAppend:Double = 0.0
            for var index=0; index < results.count; ++index
            {
                var res = results[index] as NSManagedObject;
                dateAppend = res.valueForKey("txtdate") as String
                //textAppend += "\tActual:"
                timeAppend = res.valueForKey("txttime") as String
                // get ngay de nhan he so
                if dateAppend == "2015/01/01" || dateAppend == "2015/04/30" || dateAppend == "2015/05/01" || dateAppend == "2015/09/02" || dateAppend == "2016/01/01"
                {
                    timeAfterAppend = String(format:"%.2f", (timeAppend as NSString).doubleValue * 3)
                }
                else
                {
                    if var weekday = getDayOfWeek(dateAppend) {
                        if weekday == 1
                        {
                            timeAfterAppend = String(format:"%.2f", (timeAppend as NSString).doubleValue * 2)
                        }
                        else if weekday == 7
                        {
                            if (timeAppend.toInt() > 8)
                            {
                                timeAfterAppend = String(format:"%.2f", (((timeAppend as NSString).doubleValue - 8) * 1.5) + 8)
                            }
                            else
                            {
                                timeAfterAppend = timeAppend
                            }
                        }
                        else
                        {
                            timeAfterAppend = String(format:"%.2f", (timeAppend as NSString).doubleValue * 1.5)
                        }
                    }
                }
                //mang.append(res.valueForKey("txttime") as String)
                textAppend = dateAppend + "\tActual:" + timeAppend + "\tAfter:" + timeAfterAppend
                mang.append(textAppend)
                // tinh tong
                timeTotalAppend += (timeAppend as NSString).doubleValue
                timeAfterTotalAppend += (timeAfterAppend as NSString).doubleValue
            }
            var totalString = "Total:\tActual:" + String(format:"%.2f", timeTotalAppend) + "\tAfter:" + String(format:"%.2f", timeAfterTotalAppend)
            mang.append(totalString)
            mang.removeAtIndex(0)
        } else {
            mang[0] = "Không có dữ liệu";
        }
        //mang = ["2015/01/01\t5.5", "2015/01/02\t5.5", "2015/01/03\t5.5", "2015/01/04\t5.5", "2015/01/05\t5.5", "2015/01/06\t5.5",
        //    "2015/01/07\t5.5", "2015/01/08\t5.5", "2015/01/09\t5.5", "2015/01/10\t5.5", "2015/01/07\t5.5", "2015/01/08\t5.5", "2015/01/09\t5.5", "2015/01/10\t5.5",
        //    "2015/01/07\t5.5", "2015/01/08\t5.5", "2015/01/09\t5.5", "2015/01/10\t5.5","2015/01/07\t5.5", "2015/01/08\t5.5", "2015/01/09\t5.5", "2015/01/10\t5.5"]
        // Uncomment the following line to preserve selection between presentations
        // self.clearsSelectionOnViewWillAppear = false

        // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
        // self.navigationItem.rightBarButtonItem = self.editButtonItem()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    // MARK: - Table view data source

    override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        // #warning Potentially incomplete method implementation.
        // Return the number of sections.
        //return 0
        return 1
    }

    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete method implementation.
        // Return the number of rows in the section.
        //return 0
        return mang.count
    }

    
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as UITableViewCell

        // Configure the cell...
        var h:Int = indexPath.row
        cell.textLabel?.text = mang[h]

        return cell
    }
    

    func getDayOfWeek(today:String)->Int? {
        let formatter  = NSDateFormatter()
        formatter.dateFormat = "yyyy/MM/dd"
        if let todayDate = formatter.dateFromString(today) {
            let myCalendar = NSCalendar(calendarIdentifier: NSGregorianCalendar)
            let myComponents = myCalendar?.component(.WeekdayCalendarUnit, fromDate: todayDate)
            let weekDay = myComponents?.hashValue
            return weekDay
        } else {
            return nil
        }
    }
    /*
    // Override to support conditional editing of the table view.
    override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
        // Return NO if you do not want the specified item to be editable.
        return true
    }
    */

    /*
    // Override to support editing the table view.
    override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
        if editingStyle == .Delete {
            // Delete the row from the data source
            tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
        } else if editingStyle == .Insert {
            // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
        }    
    }
    */

    /*
    // Override to support rearranging the table view.
    override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {

    }
    */

    /*
    // Override to support conditional rearranging of the table view.
    override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
        // Return NO if you do not want the item to be re-orderable.
        return true
    }
    */

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        // Get the new view controller using [segue destinationViewController].
        // Pass the selected object to the new view controller.
    }
    */

}
